import logging

from flask import Blueprint
from flask import jsonify
from flask import request

from airflow.patsnap.util.ding import Ding
from airflow.models.idata_alert import Alert
from airflow.www.api import exception_handle

log = logging.getLogger(__name__)

alert_bp = Blueprint('api_speech_alert', __name__)


@alert_bp.route('/alerts/<int:alert_id>', methods=['GET'])
@exception_handle
def get_alert(alert_id):
    alert = Alert.get_alert(alert_id)
    if alert:
        return jsonify(code=0, message='ok', data=alert.to_json())
    else:
        return jsonify(code=404, message='task not found', data=None)


@alert_bp.route('/alerts', methods=['GET'])
@exception_handle
def query_alert():
    page = request.args.get('project_id', None)
    page_size = request.args.get('page_size', 10)
    if page:
        result_obj = Alert.query_page(page, per_page=page_size)
        return jsonify(code=0, message='ok', data=result_obj.to_json())
    else:
        rs = [alert.to_json() for alert in Alert.query()]
        return jsonify(code=0, message='ok', data=rs)


@alert_bp.route('/alerts/<int:alert_id>', methods=['PUT'])
@exception_handle
def update_alert(alert_id):
    data = request.get_json()
    if 'id' not in data:
        data['id'] = alert_id
    alert = Alert(**data)
    alert.update()
    return jsonify(code=0, message='ok', data=alert.to_json())


@alert_bp.route('/alerts', methods=['POST'])
@exception_handle
def insert_alert():
    data = request.get_json()
    alert = Alert(**data)
    alert.insert()
    return jsonify(code=0, message='ok', data=alert.to_json())


@alert_bp.route('/alerts/<int:alert_id>/send', methods=['POST'])
@exception_handle
def send_alert(alert_id):
    alert = Alert.get_alert(alert_id)
    if alert is None:
        return jsonify(code=404, message='alert not found', data=None)
    if alert and alert.category == 0:
        Ding(alert.content, 'This is test alert').send()
        return jsonify(code=0, message='ok', data=alert.to_json())
